package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.user.client.VipServiceConfigFeignClient;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private VipServiceConfigFeignClient vipServiceConfigFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private UserAccountFeignClient userAccountFeignClient;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private RedissonClient redissonClient;

    //提交订单接口
    @Override
    public String submitOrder(OrderInfoVo orderInfoVo, Long userId) {
        //1 校验数据签名，判断数据是否篡改
        // orderInfoVo -- map
        //orderInfoVo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        String jsonString = JSON.toJSONString(orderInfoVo);
        Map map = JSON.parseObject(jsonString, Map.class);
        map.put("payWay",SystemConstant.ORDER_PAY_WAY_WEIXIN);
        SignHelper.checkSign(map);

        //2 判断是否重复提交
        //获取传递过来tradeNo值
        String tradeNo = orderInfoVo.getTradeNo();
        //使用lua脚本保证原子性，完成下面过程
        //根据userId 查询redis，查询存储tradeNo
        //比较两个值是否相同，如果相同，删除redis数据，第一次提交。
        //                   如果不相同，重复提交
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        String script = "if(redis.call('get', KEYS[1]) == ARGV[1]) " +
                " then return redis.call('del', KEYS[1]) " +
                " else return 0 " +
                " end";
        redisScript.setScriptText(script);
        redisScript.setResultType(Boolean.class);
        //执行
        String key = "user:trade:" + userId;
        Boolean flag = (Boolean) redisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList(key), tradeNo);
        //        Boolean flag = (Boolean)redisTemplate.
        //                       execute(redisScript, Arrays.asList(key), tradeNo);
        if(!flag) { //重复提交
            throw new GuiguException(ResultCodeEnum.ORDER_SUBMIT_REPEAT);
        }

        //判断支付方式
        //生成订单编号
        String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
        //1101-微信 1102-支付宝 1103-账户余额
        String payWay = orderInfoVo.getPayWay();
        if(!"1103".equals(payWay)) {//微信 支付宝支付
            //生成订单，未支付状态
            this.saveOrder(orderInfoVo,userId,orderNo);

        } else { //余额支付
            //1 远程调用： 检查余额是否充足，扣减余额
            //根据最终订单金额 orderAmount，到user_account表查询
            AccountLockVo accountDeductVo = new AccountLockVo();
            accountDeductVo.setOrderNo(orderNo);
            accountDeductVo.setUserId(userId);
            accountDeductVo.setAmount(orderInfoVo.getOrderAmount());
            accountDeductVo.setContent(orderInfoVo.getOrderDetailVoList()
                                                      .get(0).getItemName());
            //检查与扣减账户金额
            Result result = userAccountFeignClient.checkAndDeduct(accountDeductVo);
            if(result.getCode()!=200) { //余额不足
                throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
            }

            //检查与扣减账户金额成功
            //创建订单（未支付）
            OrderInfo orderInfo = this.saveOrder(orderInfoVo,userId,orderNo);

            //远程调用：添加购买记录
            //  创建用户购买记录对象
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            //  记录用户购买信息
            userPaidRecordVo.setOrderNo(orderNo);
            userPaidRecordVo.setUserId(orderInfo.getUserId());
            //购买类型 ：vip 专辑 声音
            userPaidRecordVo.setItemType(orderInfo.getItemType());
            //  购买项目的Id 专辑Id，声音Id（多个）, vip的id
            List<Long> itemIdList = orderInfoVo.getOrderDetailVoList()
                    .stream().map(OrderDetailVo::getItemId)
                    .collect(Collectors.toList());
            userPaidRecordVo.setItemIdList(itemIdList);
            //远程调用：
            Result userResult =
                    userInfoFeignClient.savePaidRecord(userPaidRecordVo);
            if (200 != userResult.getCode()) {
                throw new GuiguException(211, "新增购买记录异常");
            }
            //购买记录添加成功 ，根据订单编号修改订单状态（已经支付）
            this.orderPaySuccess(orderNo);
        }
        return orderNo;
    }

    //根据订单编号修改订单状态
    public void orderPaySuccess(String orderNo) {
        //根据订单编号查询订单对象
        OrderInfo orderInfo = this.getOrderInfoByOrderNo(orderNo);
        //订单状态是未支付修改
        if (orderInfo.getOrderStatus().equals("0901")) {
            //订单对象设置订单状态值 0902
            //SystemConstant.ORDER_STATUS_PAID
            orderInfo.setOrderStatus("0902");

            //调用方法进行修改
            orderInfoMapper.updateById(orderInfo);
        }
    }

    //根据订单编号查询订单对象
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);

        //根据订单id查询明细数据
        Long orderId = orderInfo.getId();
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);

        //设置到订单对象里面
        orderInfo.setOrderDetailList(orderDetails);

        orderInfo.setPayWayName(this.getPayWayName(orderInfo.getPayWay()));

        return orderInfo;
    }

    @Override
    public IPage<OrderInfo> findUserPage(Page<OrderInfo> pageParam, Long userId) {
        //  调用mapper 层方法
        IPage<OrderInfo> infoIPage = orderInfoMapper.selectUserPage(pageParam,userId);
        infoIPage.getRecords().forEach(item->{
            //  设置状态名
            item.setOrderStatusName(getOrderStatusName(item.getOrderStatus()));
            item.setPayWayName(getPayWayName(item.getPayWay()));
        });
        return infoIPage;
    }

    //根据订单编号修改订单状态（已经支付），远程调用添加购买记录
    @Override
    public void updateOrderSuccess(String orderNo) {
        //根据订单编号修改订单状态（已经支付）
        //根据订单编号查询订单对象
        OrderInfo orderInfo = this.getOrderInfoByOrderNo(orderNo);
        //订单状态是未支付修改
        if (orderInfo.getOrderStatus().equals("0901")) {
            //订单对象设置订单状态值 0902
            //SystemConstant.ORDER_STATUS_PAID
            orderInfo.setOrderStatus("0902");

            //调用方法进行修改
            orderInfoMapper.updateById(orderInfo);
        }

        //远程调用添加购买记录
        UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
        userPaidRecordVo.setOrderNo(orderNo);
        userPaidRecordVo.setUserId(orderInfo.getUserId());
        userPaidRecordVo.setItemType(orderInfo.getItemType());
        List<Long> itemIdList =
                orderInfo.getOrderDetailList().stream().map(OrderDetail::getItemId).collect(Collectors.toList());
        userPaidRecordVo.setItemIdList(itemIdList);

        userInfoFeignClient.savePaidRecord(userPaidRecordVo);
    }


    /**
     * 根据订单状态获取到订单名称
     * @param orderStatus
     * @return
     */
    private String getOrderStatusName(String orderStatus) {
        //  声明订单状态名称
        String orderStatusName = "";
        //  判断
        if (SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus)){
            orderStatusName = "未支付";
        } else if (SystemConstant.ORDER_STATUS_PAID.equals(orderStatus)) {
            orderStatusName = "已支付";
        } else {
            orderStatusName = "已取消";
        }
        //  返回
        return orderStatusName;
    }

    /**
     * 根据payWay 返回支付名称
     * @param payWay
     * @return
     */
    private String getPayWayName(String payWay) {
        //  声明一个对象
        return
                SystemConstant.ORDER_PAY_WAY_WEIXIN.equals(payWay)
                        ?"微信支付"
                        :"余额支付";
    }

    //调用方法，根据orderId取消订单
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        //订单未支付，进行取消
        if(orderInfo.getOrderStatus().equals("0901")) {
            orderInfo.setOrderStatus("0903");
            orderInfoMapper.updateById(orderInfo);
        }
    }

    @Autowired
    private OrderDerateMapper orderDerateMapper;
    //创建订单
    private OrderInfo saveOrder(OrderInfoVo orderInfoVo, Long userId, String orderNo) {
        //order_info: 订单基本信息
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoVo, orderInfo);
        orderInfo.setOrderNo(orderNo);//订单编号
        //订单名称
        List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
        String itemName = orderDetailVoList.get(0).getItemName();
        orderInfo.setOrderTitle(itemName);
        //userId
        orderInfo.setUserId(userId);
        //订单状态 0901-未支付 0902-已支付 0903-已取消
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);
        //调用方法
        orderInfoMapper.insert(orderInfo);

        //order_detail：订单明细
        if (!CollectionUtils.isEmpty(orderInfoVo.getOrderDetailVoList())) {
            orderInfoVo.getOrderDetailVoList().forEach(orderDetailVo -> {
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(orderDetailVo, orderDetail);
                orderDetail.setOrderId(orderInfo.getId());
                orderDetailMapper.insert(orderDetail);
            });
        }

        //order_derate：优惠明细
        if (!CollectionUtils.isEmpty(orderInfoVo.getOrderDerateVoList())) {
            orderInfoVo.getOrderDerateVoList().forEach(orderDerateVo -> {
                OrderDerate orderDerate = new OrderDerate();
                BeanUtils.copyProperties(orderDerateVo, orderDerate);
                orderDerate.setOrderId(orderInfo.getId());
                orderDerateMapper.insert(orderDerate);
            });
        }

        //如果不是余额支付，发送延迟消息
        //1101-微信 1102-支付宝 1103-账户余额"
        String payWay = orderInfoVo.getPayWay();
        if(!"1103".equals(payWay)) {
            //发送延迟消息，30分钟不支付订单自动取消
            Long orderId = orderInfo.getId();
            this.sendDelayMessage(orderId);
        }
        return orderInfo;
    }

    //延迟消息
    private void sendDelayMessage(Long orderId) {
        //1 使用redissonClient创建普通队列
        RBlockingQueue<Object> blockingQueue =
                redissonClient.getBlockingQueue(MqConst.EXCHANGE_CANCEL_ORDER);

        //2 把普通队列变成延迟队列
        RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);

        //3 向延迟队列添加消息，设置消息过期时间
        delayedQueue.offer(orderId.toString(),30,TimeUnit.MINUTES);
        //TODO 为了测试 10s
        //delayedQueue.offer(orderId.toString(),10,TimeUnit.SECONDS);
    }

    //跳转结算页面
    @Override
    public OrderInfoVo trade(TradeVo tradeVo, Long userId) {
        //1 远程调用：根据userId获取用户信息
        Result<UserInfoVo> resultUserInfoVo =
                           userInfoFeignClient.getUserInfoVo(userId);
        UserInfoVo userInfoVo = resultUserInfoVo.getData();
        Assert.notNull(userInfoVo,"用户信息为空");

        //  订单原始金额
        BigDecimal originalAmount = new BigDecimal("0.00");
        //  减免总金额
        BigDecimal derateAmount = new BigDecimal("0.00");
        //  订单总价
        BigDecimal orderAmount = new BigDecimal("0.00");
        //  订单明细集合
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        //  订单减免明细列表
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //2 获取购买类型 tradeVo里面itemType
        //1001-专辑 1002-声音 1003-vip会员
        String itemType = tradeVo.getItemType();
        //3 购买专辑
        if("1001".equals(itemType)) {
            //3.1 远程调用：判断用户是否购买过专辑，
            Result<Boolean> resultUserPaid =
                    userInfoFeignClient.isPaidAlbum(tradeVo.getItemId());
            Boolean isPaid = resultUserPaid.getData();
            if(isPaid) { //如果用户购买过，不需要购买
                throw new GuiguException(300,"专辑购买过");
            }

            //3.2 根据专辑id获取专辑信息 tradeVo里面itemId
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(tradeVo.getItemId());
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo,"专辑数据为空");

            //3.3 判断当前用户如果不是vip,使用普通折扣，获取原始金额，计算优惠金额和最终金额
            Integer isVip = userInfoVo.getIsVip();
            if(isVip.intValue()==0) { //如果不是vip,使用普通折扣
                //获取原始价格
                originalAmount = albumInfo.getPrice();
                //计算优惠金额
                //获取折扣
                BigDecimal discount = albumInfo.getDiscount();
                if(discount.intValue()!=-1) { //打折
                    // 原始金额 * (10-折扣) / 10
                    derateAmount = originalAmount.multiply(
                            new BigDecimal("10").subtract(discount))
                            .divide(new BigDecimal(10),2,RoundingMode.HALF_UP);
                }
                //最终金额 = 原始金额 - 优惠金额
                orderAmount = originalAmount.subtract(derateAmount);

            } else if(isVip.intValue()==1 && userInfoVo.getVipExpireTime().before(new Date())) {
                 //如果是vip但是vip过期了,使用普通折扣
                //获取原始价格
                originalAmount = albumInfo.getPrice();
                //计算优惠金额
                //获取折扣
                BigDecimal discount = albumInfo.getDiscount();
                if(discount.intValue()!=-1) { //打折
                    // 原始金额 * (10-折扣) / 10
                    derateAmount = originalAmount.multiply(
                                    new BigDecimal("10").subtract(discount))
                            .divide(new BigDecimal(10),2,RoundingMode.HALF_UP);
                }
                //最终金额 = 原始金额 - 优惠金额
                orderAmount = originalAmount.subtract(derateAmount);

            } else {
                //3.3 判断当前用户如果是vip,使用vip折扣，获取原始金额，计算优惠金额和最终金额
                //是vip，使用vip折扣
                BigDecimal vipDiscount = albumInfo.getVipDiscount();
               ///获取原始价格
                originalAmount = albumInfo.getPrice();
                //计算优惠金额
                //获取折扣
                if(vipDiscount.intValue()!=-1) { //打折
                    // 原始金额 * (10-折扣) / 10
                    derateAmount = originalAmount.multiply(
                                    new BigDecimal("10").subtract(vipDiscount))
                            .divide(new BigDecimal(10),2,RoundingMode.HALF_UP);
                }
                //最终金额 = 原始金额 - 优惠金额
                orderAmount = originalAmount.subtract(derateAmount);
            }

            //3.4 封装其他数据
            //订单明细列表
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(albumInfo.getPrice());
            orderDetailVoList.add(orderDetailVo);

            //订单减免明细列表
            //原始金额 - 最终金额 !=0
            if (originalAmount.subtract(orderAmount).doubleValue() != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setDerateAmount(originalAmount.subtract(orderAmount));
                orderDerateVoList.add(orderDerateVo);
            }

        } else if("1003".equals(itemType)) { //4 购买vip
            //4.1 根据开通vip的id tradeVo里面itemId获取vip信息
            //  根据id 获取VIP 服务配置信息
            Result<VipServiceConfig> vipServiceConfigResult =
                    vipServiceConfigFeignClient.getVipServiceConfig(tradeVo.getItemId());
            VipServiceConfig vipServiceConfig = vipServiceConfigResult.getData();
            Assert.notNull(vipServiceConfig,"返回vip配置对象不能为空");

            //4.2 获取原始金额，计算优惠金额和最终金额
            originalAmount = vipServiceConfig.getPrice();
            orderAmount = vipServiceConfig.getDiscountPrice();
            derateAmount = originalAmount.subtract(orderAmount);

            //4.3 封装其他数据
            //订单明细
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName("VIP会员"+vipServiceConfig.getName());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemPrice(vipServiceConfig.getDiscountPrice());
            orderDetailVoList.add(orderDetailVo);

            //添加订单减免
            if (originalAmount.subtract(orderAmount).doubleValue() != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
                orderDerateVo.setDerateAmount(originalAmount.subtract(orderAmount));
                orderDerateVoList.add(orderDerateVo);
            }
        } else if("1002".equals(itemType)) {
            //5 购买声音
            Integer trackCount = tradeVo.getTrackCount();
            if(trackCount.intValue()<0) {
                throw new GuiguException(ResultCodeEnum.DATA_ERROR);
            }
            
            //获取本集声音id
            Long itemId = tradeVo.getItemId();
            //远程调用：根据本集id + trackCount（购买集数）获取声音列表数据
            // 过滤掉购买过声音
            Result<List<TrackInfo>> result =
                    trackInfoFeignClient.findPaidTrackInfoList(itemId,trackCount);
            List<TrackInfo> trackInfoList = result.getData();

            //因为声音单价在专辑数据里面，获取专辑对象数据
            Long albumId = trackInfoList.get(0).getAlbumId();
            Result<AlbumInfo> albumInfoResult =
                       albumInfoFeignClient.getAlbumInfo(albumId);
            AlbumInfo albumInfo = albumInfoResult.getData();

            //购买声音没有折扣，实际金额和最终金额相同的
            //trackCount=0购买本集，trackCount>0 购买很多集，单价*数量
            originalAmount =
                    trackCount.intValue()>0
                            ? albumInfo.getPrice().multiply(new BigDecimal(trackCount))
                            : albumInfo.getPrice();
            //最终价格
            orderAmount = originalAmount;

            //封装订单明细
            //List<TrackInfo>  -- List<OrderDetailVo>
            orderDetailVoList = trackInfoList.stream().map(trackInfo -> {
                OrderDetailVo orderDetailVo = new OrderDetailVo();
                orderDetailVo.setItemName(trackInfo.getTrackTitle());
                orderDetailVo.setItemId(trackInfo.getId());
                orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
                orderDetailVo.setItemPrice(albumInfo.getPrice());
                return orderDetailVo;
            }).collect(Collectors.toList());

        }

        //6 把最终的数据封装到OrderInfoVo，返回OrderInfoVo对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //购买类型：vip  专辑  声音
        orderInfoVo.setItemType(tradeVo.getItemType());
        //原始金额
        orderInfoVo.setOriginalAmount(originalAmount);
        //优惠金额
        orderInfoVo.setDerateAmount(derateAmount);
        //最终金额
        orderInfoVo.setOrderAmount(orderAmount);
        //订单明细和优惠明细
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        //时间
        orderInfoVo.setTimestamp(SignHelper.getTimestamp());

        //  支付方式  //"1101"
        orderInfoVo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);

        //7 防止重复提交
        //向redis添加数据
        String key = "user:trade:" + userId;
        String value = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(key,value);
        //orderInfoVo设置value值
        orderInfoVo.setTradeNo(value);

        //8 对生成订单提交数据加密处理，防止数据被修改
        //对orderInfoVo数据加密
        // orderInfoVo -- map
        String jsonString = JSON.toJSONString(orderInfoVo);
        Map<String, Object> parameterMap = JSON.parseObject(jsonString, Map.class);
        String sign = SignHelper.getSign(parameterMap);

        //把加密之后字符串设置到orderInfoVo
        orderInfoVo.setSign(sign);

        return orderInfoVo;
    }

}
